package com.yuwei.security.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 验证码过滤器
 */
public class YzmCodeFilter extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(YzmCodeFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String expect = (String) request.getSession().getAttribute("VERIFY_CODE");
        logger.info("验证用户请求验证码，请求值:{},本地缓存:{}",request.getParameter("VERIFY_CODE"),expect);

        if(null == expect){
            checkyzmCodeFail(response,"请输入验证码");
            return;
        }
        if (!expect.equalsIgnoreCase(request.getParameter("VERIFY_CODE"))) {
            request.getSession().removeAttribute("VERIFY_CODE");
            checkyzmCodeFail(response,"验证码不正确");
            return;
        }

        LocalDateTime createTime = (LocalDateTime) request.getSession().getAttribute("VERIFY_CODE_CREATE_AT");
        Duration between = Duration.between(createTime,LocalDateTime.now());
        if(between.getSeconds()>60){
            checkyzmCodeFail(response,"验证码过期");
            return;
        }
        request.getSession().removeAttribute("VERIFY_CODE");
        //放行
        filterChain.doFilter(request, response);
    }

    private void checkyzmCodeFail(HttpServletResponse response, String errMsg) throws IOException {
        //设置返回请求头
        response.setStatus(HttpServletResponse.SC_OK);
        //写出流
        response.getWriter().write(errMsg);
    }

}
